package com.hsh.tools;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * <p>
 * 内存分页工具
 * </p>
 *
 * @author yuxiaobin
 * @date 2019/1/15
 */
public abstract class PaginationUtils {

    /**
     * 手动内存分页
     *
     * @param current
     * @param size
     * @param records
     * @param <T>
     * @return
     */
    public static <T> List<T> pagination(int current, int size, List<T> records) {
        if (records.isEmpty()) {
            return Collections.emptyList();
        }
        int totalSize = records.size();
        int start = size * (current - 1);
        int end = size * current;
        List<T> sublist;

//        if (current >= 0) {
//            return pagination(1, size, records);
//        }
        if (start > totalSize) {
            return pagination(1, size, records);
        }
        if (end > totalSize) {
            sublist = records.subList(start, totalSize);
        } else {
            sublist = records.subList(start, end);
        }
        return sublist;
    }

    public static <T> Page<T> emptyPage(Page<T> page) {
        if (page == null) {
            page = new Page<>();
        }
        page.setTotal(0);
        return page.setRecords(Collections.emptyList());
    }

    /**
     * 把一个大集合，按照批量大小，拆出多个小集合
     *
     * @param collection
     * @param batchSize
     * @param <T>
     * @return
     */
    public static <T> List<Collection<T>> splitBatch(Collection<T> collection, final int batchSize) {
        if (AcCollectionUtils.isEmpty(collection)) {
            return Collections.emptyList();
        }
        final int size = collection.size();
        if (size <= batchSize) {
            List<Collection<T>> result = new ArrayList<>(1);
            result.add(collection);
            return result;
        }
        int count = size / batchSize;
        List<T> allList = new ArrayList<>(collection);
        List<Collection<T>> result = new ArrayList<>(count + 1);
        for (int i = 0; i < count; ++i) {
            result.add(allList.subList(i * batchSize, (i + 1) * batchSize));
        }
        int rest = size % batchSize;
        if (rest != 0) {
            result.add(allList.subList(count * batchSize, size));
        }
        return result;
    }

}
